<?php

namespace App\Http\Controllers\Mp;

use App\Models\User;
use Illuminate\Http\Request;
use Overtrue\LaravelWeChat\Facade;

/**
 * Class TokenController
 * @package App\Http\Controllers\Mp
 * @author zjw
 */
class TokenController extends BaseController
{
    public function store(Request $request)
    {
        if ($code = $request->wx_code) {
            $app = Facade::miniProgram();
            $session = $app->auth->session($code);
            if (!array_get($session, 'errcode')) {
                $openid = array_get($session, 'openid');
                $user = User::query()->where('status', User::ACTIVE)->where("mp_openid", $openid)->first();
                if (!$user) {
                    return $this->fail('用户不存在');
                }
            } else {
                return $this->fail('用户不存在');
            }
        } else {
            $phone = $request->phone;
            if (!$phone) {
                return $this->fail('手机号码不能为空');
            }
            $code = $request->get('code');
            if (!$code) {
                return $this->fail('验证码不能为空');
            }
            if (\Cache::get("login_code:" . $phone) != $code) {
                return $this->fail('验证码不正确');
            }
            $user = User::query()->where('status', User::ACTIVE)->where("phone", $phone)->first();
        }
        $token = str_random(40);
        $user->auth_token = $token;
        if ($user->save()) {
            return [
                'token' => $token,
            ];
        } else {
            return $this->fail('未知错误');
        }
    }
}
